package com.tianhui.consignortwofei.mvp.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.fgs.common.CommonPresenter;
import com.fgs.common.CommonResponse;
import com.fgs.common.CommonView;
import com.fgs.common.manager.ActivityManager;
import com.fgs.common.progress.ExceptionHandle;
import com.fgs.common.progress.ObserverResponseListener;
import com.fgs.common.utils.CheckUtil;
import com.fgs.common.utils.CountDownTimerUtil;
import com.fgs.common.utils.ToastUtil;
import com.fgs.common.webViewInter.OpenWeb;
import com.fgs.common.webViewInter.PrivacyPolicyWebInfo;
import com.fgs.common.webViewInter.UserAgreementWebInfo;
import com.fgs.common.widget.TextChange;
import com.google.gson.reflect.TypeToken;
import com.tianhui.consignortwofei.R;
import com.tianhui.consignortwofei.base.BaseActivity;
import com.tianhui.consignortwofei.base.BaseFragment;
import com.tianhui.consignortwofei.constant.KeyValue;
import com.tianhui.consignortwofei.manager.SharedPreferenceManager;
import com.tianhui.consignortwofei.mvp.model.AccountModel;
import com.tianhui.consignortwofei.mvp.model.AuthCodeModel;
import com.tianhui.consignortwofei.mvp.model.enty.CaptchaInfo;
import com.tianhui.consignortwofei.mvp.model.enty.LoginInfo;
import com.tianhui.consignortwofei.mvp.model.enty.RegisterInfo;
import com.tianhui.consignortwofei.other.AuthCode;
import com.xuexiang.xui.widget.edittext.ClearEditText;
import com.xuexiang.xui.widget.edittext.PasswordEditText;
import com.xuexiang.xutil.net.JsonUtil;
import com.xuexiang.xutil.security.Base64Utils;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author fgs
 * @date 2020/3/27
 **/
public class RegisterActivity extends BaseActivity {

    @BindView(R.id.layout_register_forget_password_logoTipLinearLayout)
    LinearLayout logoTipLinearLayout;
    @BindView(R.id.layout_register_forget_password_logoTipTextView)
    TextView logoTipTextView;
    @BindView(R.id.layout_register_forget_password_phoneClearEditText)
    ClearEditText phoneClearEditTextView;
    @BindView(R.id.layout_register_forget_password_codeEditText)
    ClearEditText codeEditText;
    @BindView(R.id.layout_register_forget_password_codeTextView)
    TextView codeTextView;
    @BindView(R.id.layout_register_forget_password_passwordEditText)
    PasswordEditText passwordEditText;
    @BindView(R.id.activity_register_checkBox)
    CheckBox registerCheckBox;
    @BindView(R.id.activity_register_registerButton)
    Button registerButton;
    private AccountModel accountModel;
    private AuthCodeModel authCodeModel;
    private CountDownTimerUtil mCountDownTimerUtil;
    private boolean isAgree;
    private String mPhone;

    @Override
    public int getLayoutId() {
        return R.layout.activity_register;
    }

    @Override
    public CommonPresenter createPresenter() {
        return null;
    }

    @Override
    public CommonView createView() {
        return null;
    }

    @Override
    public String getToolbarTitle() {
        return "";
    }

    @Override
    public void init() {

        logoTipTextView.setText("欢迎注册");

        logoTipLinearLayout.setVisibility(View.VISIBLE);

        accountModel = new AccountModel();
        authCodeModel = new AuthCodeModel();

        registerCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isAgree = !isAgree;
            }
        });

        new TextChange.Builder()
                .addEditText(phoneClearEditTextView, 11)
                .addEditText(codeEditText, 6)
                .addEditText(passwordEditText, 6)
                .addListenView(registerButton)
                .build();

        getToolbarStatus().getToolbarOptions().getToolbar().setBackgroundColor(getResources().getColor(R.color.colorWhite));
        getToolbarStatus().setBackIconImageView(R.mipmap.icon_back_black);

    }

    @Override
    public BaseFragment createFragment() {
        return null;
    }

    @OnClick(R.id.activity_register_registerButton)
    public void register() {
        mPhone = phoneClearEditTextView.getText().toString().trim();
        String code = codeEditText.getText().toString().trim();
        String password = passwordEditText.getText().toString().trim();

        if (TextUtils.isEmpty(mPhone)) {
            ToastUtil.showShortToast("请输入手机号");
            return;
        }

        if (!CheckUtil.isMobileNO(mPhone)) {
            ToastUtil.showShortToast("请输入正确的手机号");
            return;
        }

        if (TextUtils.isEmpty(code)) {
            ToastUtil.showShortToast("请输入验证码");
            return;
        }
        if (code.length() < 6) {
            ToastUtil.showShortToast("验证码不能少与6位");
            return;
        }

        if (TextUtils.isEmpty(password)) {
            ToastUtil.showShortToast("请输入密码");
            return;
        }
        if (password.length() < 8) {
            ToastUtil.showShortToast("密码不能少与8位");
            return;
        }

//        if (!CheckUtil.isPasswordStrength(password)) {
//            ToastUtil.showShortToast("密码必须包含字母和数字");
//            return;
//        }

        RegisterInfo info = new RegisterInfo();
        info.customertel = "+86" + mPhone;
        info.customerpassword = Base64Utils.encode(password);
        info.code = code;

        if (!isAgree) {
            showToast("请先阅读并同意用户协议和隐私政策");
            return;
        }

        requestRegister(info);


    }

    private void requestRegister(RegisterInfo info) {


        accountModel.registerModel(RegisterActivity.this, info, true, true, this.bindToLifecycle(), new ObserverResponseListener<CommonResponse>() {
            @Override
            public void onNext(CommonResponse commonResponse) {
                if (commonResponse.getCode() == 20000) {
                    showToast("注册成功");
                    SharedPreferenceManager.getInstance().setAccountNumber(mPhone);
                    requestLogin(info);
                } else {
                    showToast(commonResponse.getMsg());
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                showToast(e.message);
            }
        });
    }

    private void requestLogin(RegisterInfo info) {
        Map<String, String> map = new HashMap<>();
//        if (info == null) {
//            map.put("username", mPhone);
//            map.put("password", Base64Utils.encode("th123456"));
//
//        } else {
        map.put("username", mPhone);
        map.put("password", info.customerpassword);
        map.put("type", "1,2");

//        }
        SharedPreferenceManager.getInstance().setAccountNumber(mPhone);
        accountModel.loginModel(this, map, true, this.bindLifecycle(), new ObserverResponseListener<CommonResponse>() {
            @Override
            public void onNext(CommonResponse commonResponse) {
                if (commonResponse.getCode() == 20000) {
                    LoginInfo info = JsonUtil.fromJson(commonResponse.getData().toString(), new TypeToken<LoginInfo>() {
                    }.getType());
                    result(info);
                } else {
//                    showToast(commonResponse.getMsg());
                    registerResult();
                }

            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
//                showToast(e.message);
                registerResult();
            }
        });
    }

    private void registerResult() {
        Intent intent = getIntent();
        Bundle bundle = new Bundle();
        bundle.putString(KeyValue.KEY_PHONE, mPhone);
        intent.putExtras(bundle);
        setResult(KeyValue.KEY_RESULT_CODE, intent);
        showToast("注册成功");
        finish();
    }

    private void result(LoginInfo info) {
        SharedPreferenceManager.getInstance().setToken(info.token);
        ActivityManager.getInstance().finishActivity(LoginActivityNew.class);
        openActivity(MainActivity.class);
//        new MaterialDialog.Builder(this)
//                .content("账号注册完成，是否继续填写认证信息")
//                .positiveText("是")
//                .negativeText("否")
//                .onPositive(new MaterialDialog.SingleButtonCallback() {
//                    @Override
//                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
////                        openActivity(AllAuthInfoActivity.class);
//                        finish();
//                    }
//                })
//                .onNegative(new MaterialDialog.SingleButtonCallback() {
//                    @Override
//                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//                        openActivity(MainActivity.class);
//                        finish();
//                    }
//                })
//                .show();


    }

    @OnClick(R.id.layout_register_forget_password_codeTextView)
    public void getAuthCode() {
        String phone = phoneClearEditTextView.getText().toString().trim();

        new AuthCode(this, phone).authCode(new AuthCode.OnAuthCodeCallback() {
            @Override
            public void onAuthCallback(CaptchaInfo info) {
                if (info.ret == 0) {
                    info.mobile = "+86" + phone;
                    info.action = "driverRegister";
                    requestAuthCode(info);

                }
            }
        });

    }

    private void requestAuthCode(CaptchaInfo info) {
        authCodeModel.authCodeModel(this, info, true, this.bindToLifecycle(), new ObserverResponseListener<CommonResponse>() {
            @Override
            public void onNext(CommonResponse commonResponse) {
                if (commonResponse.getCode() == 20000) {
                    showToast("获取验证码成功");
                    startCountDownTime();
                } else {
                    showToast(commonResponse.getMsg());
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                showToast(e.message);
            }
        });
    }

    private void startCountDownTime() {
        mCountDownTimerUtil = new CountDownTimerUtil(codeTextView, 1000 * 60, 1000);
        mCountDownTimerUtil.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mCountDownTimerUtil != null) {
            mCountDownTimerUtil.timeCancel();
        }
    }

    @OnClick(R.id.activity_register_userAgreementTextView)
    public void userAgreement() {
        OpenWeb openWeb = new OpenWeb();
        openWeb.openWebView(this, new UserAgreementWebInfo());
    }

    @OnClick(R.id.activity_register_loginTextView)
    public void login() {
        finish();
    }

    @OnClick(R.id.activity_register_privacyPolicyTextView)
    public void privacyPolicy() {
        OpenWeb openWeb = new OpenWeb();
        openWeb.openWebView(this, new PrivacyPolicyWebInfo());
    }

}
